'''
通过话题发布小说

'''
import rclpy
from rclpy.node import Node
import requests
from example_interfaces.msg import String
from queue import Queue


class NovelPubNode(Node):
    def __init__(self,node_name):
        Node.__init__(self,node_name)
        self.get_logger().info(f'{node_name}开始运行')
        self.novel_queue = Queue()  # 创建将存储小说的队列
        self.novel_publisher = self.create_publisher(String,"novel",10)
        self.create_timer(5,self.novel_publish)  # 创建发布小说信息的定时器

    def novel_publish(self):
        if not self.novel_queue.empty():
            novel_line = self.novel_queue.get()
            self.get_logger().info(f'{novel_line}')
            msg = String()
            msg.data = novel_line
            self.novel_publisher.publish(msg)

    
    def download_novel(self,url):
        self.get_logger().info(f'{url}:开始下载小说')
        response = requests.get(url)
        response.encoding = 'utf-8'
        if response.status_code == 200:
            self.get_logger().info(f'{url}:下载小说成功')
            for  line in response.text.splitlines():  # 将小说每一行放进添加到队列中
                self.novel_queue.put(line)
        else:
            self.get_logger().info(f'{url}:下载小说失败')


def main():
    rclpy.init()
    node = NovelPubNode("novel_pub")
    node.download_novel("http://0.0.0.0:8000/novel1.txt")
    rclpy.spin(node)
    rclpy.shutdown()